package com.qumitech.visualnovel.service.accompany.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.exception.BusinessException;
import com.qumitech.visualnovel.component.util.ExcelUtils;
import com.qumitech.visualnovel.component.util.FileUtil;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.accompany.admin.*;
import com.qumitech.visualnovel.pubdef.dto.accompany.admin.query.AccompanyAfterSaleApplyQueryAdminDTO;
import com.qumitech.visualnovel.pubdef.dto.accompany.admin.query.AccompanyAppraiseQueryAdminDTO;
import com.qumitech.visualnovel.pubdef.dto.accompany.admin.query.AccompanyOrderQueryAdminDTO;
import com.qumitech.visualnovel.service.accompany.AccompanyService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AccompanyServiceImpl implements AccompanyService {
    private static final String ListOrderUrl = "/admin/accompany/order";
    private static final String ListAppealUrl = "/admin/accompany/appeal";
    private static final String ListAppraiseUrl = "/admin/accompany/appraise";
    private static final String AuditAppealUrlFormat = "/admin/accompany/order/%s/appeal/audit";
    private static final String AuditAppraiseUrlFormat = "/admin/accompany/order/appraise/audit";

    @Override
    public BaseRsp listAdminAccompanyOrder(AccompanyOrderQueryAdminDTO queryAdminDTO) {
        String url = String.format("%s%s", UrlConstant.SERVER_URL, ListOrderUrl);
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryAdminDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public Map<String, Object> listAccompanyOrderExport(AccompanyOrderQueryAdminDTO queryAdminDTO,
                                                         HttpServletResponse response) {
        BaseRsp rsp = listAdminAccompanyOrder(queryAdminDTO);
        Map<String, Object> rspMap = (Map<String, Object>) rsp.getData();
        Map<String, Object> resultMap = new HashMap<>(16);

        try {
            JSONArray orderList = (JSONArray) rspMap.get("orders");
            List<AccompanyOrderExportDTO> accompanyOrders = new ArrayList<>(16);
            for (int i = 0; i < orderList.size(); i++) {
                AccompanyOrderExportDTO exportDTO = new AccompanyOrderExportDTO();
                exportDTO.setOrderNo((String) orderList.getJSONObject(i).get("order_no"));
                exportDTO.setUid(orderList.getJSONObject(i).get("uid").toString());
                exportDTO.setUserName((String) orderList.getJSONObject(i).get("user_name"));
                exportDTO.setToUid(orderList.getJSONObject(i).get("to_uid").toString());
                exportDTO.setToUserName((String) orderList.getJSONObject(i).get("to_user_name"));
                if (orderList.getJSONObject(i).get("skill_id") != null) {
                    exportDTO.setSkillId(orderList.getJSONObject(i).get("skill_id").toString());
                }
                exportDTO.setSkillName((String) orderList.getJSONObject(i).get("skill_name"));
                exportDTO.setSkillIcon((String) orderList.getJSONObject(i).get("skill_icon"));
                exportDTO.setSkillPriceBase((String) orderList.getJSONObject(i).get("skill_price_base"));
                exportDTO.setOrderNum(orderList.getJSONObject(i).get("order_num").toString());
                exportDTO.setOriginPrice(orderList.getJSONObject(i).get("origin_price").toString());
                exportDTO.setFinalPrice(orderList.getJSONObject(i).get("final_price").toString());
                if (orderList.getJSONObject(i).get("coupon_id") != null) {
                    exportDTO.setCouponId(orderList.getJSONObject(i).get("coupon_id").toString());
                }
                exportDTO.setCouponName((String) orderList.getJSONObject(i).get("coupon_name"));
                exportDTO.setState(orderList.getJSONObject(i).get("state").toString());
                exportDTO.setOrderCreateTime((String) orderList.getJSONObject(i).get("order_create_time"));
                exportDTO.setOrderTakingEndTime((String) orderList.getJSONObject(i).get("order_taking_end_time"));
                exportDTO.setExpectedStartTime((String) orderList.getJSONObject(i).get("expected_start_time"));
                exportDTO.setServeEndTime((String) orderList.getJSONObject(i).get("serve_end_time"));
                exportDTO.setActualStartTime((String) orderList.getJSONObject(i).get("actual_start_time"));
                exportDTO.setActualEndTime((String) orderList.getJSONObject(i).get("actual_end_time"));
                exportDTO.setAppraiseEndTime((String) orderList.getJSONObject(i).get("appraise_end_time"));
                exportDTO.setRemark((String) orderList.getJSONObject(i).get("remark"));
                exportDTO.setCancelReason((String) orderList.getJSONObject(i).get("cancel_reason"));
                exportDTO.setCancelRemark((String) orderList.getJSONObject(i).get("cancel_remark"));
                exportDTO.setUpdateTime((String) orderList.getJSONObject(i).get("update_time"));
                exportDTO.setUnitPrice(orderList.getJSONObject(i).get("origin_price").toString(),
                        orderList.getJSONObject(i).get("order_num").toString());
                accompanyOrders.add(exportDTO);
            }

            ExcelUtils<AccompanyOrderExportDTO> xls = new ExcelUtils<>(AccompanyOrderExportDTO.class);
            String filename = FileUtil.getExcelName();
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            OutputStream outputStream = response.getOutputStream();
            xls.exportExcel("大神订单列表", accompanyOrders, outputStream);
            outputStream.flush();
            outputStream.close();
            resultMap.put("title", filename);
            return resultMap;
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new BusinessException(ResultEnum.EXCEL_EXPORT_ERROR);
    }

    @Override
    public BaseRsp listAdminAccompanyAfterSaleApply(AccompanyAfterSaleApplyQueryAdminDTO queryAdminDTO) {
        String url = String.format("%s%s", UrlConstant.SERVER_URL, ListAppealUrl);
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryAdminDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp auditAccompanyAppealOrder(AccompanyAfterSaleAuditAdminDTO auditAdminDTO) {
        String auditAppealUrl = String.format(AuditAppealUrlFormat, auditAdminDTO.getOrderNo());
        String url = String.format("%s%s", UrlConstant.SERVER_URL, auditAppealUrl);
        String req = JSONObject.toJSONString(auditAdminDTO);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp listAccompanyAppraise(AccompanyAppraiseQueryAdminDTO queryDTO) {
        String url = String.format("%s%s", UrlConstant.SERVER_URL, ListAppraiseUrl);
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp auditAccompanyAppraise(AccompanyAppraiseAuditAdminDTO auditAdminDTO) {
        String url = String.format("%s%s", UrlConstant.SERVER_URL, AuditAppraiseUrlFormat);
        String req = JSONObject.toJSONString(auditAdminDTO);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }
}
